package com.jarvis.app.car.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.jarvis.app.car.AddCarActivity;
import com.jarvis.app.car.CarInfoActivity;
import com.jarvis.app.car.R;
import com.jarvis.app.car.adapter.HomeCarItemAdapter;
import com.jarvis.app.car.common.MessageResult;
import com.jarvis.app.car.constant.AppConstant;
import com.jarvis.app.car.model.Car;
import com.jarvis.app.car.util.ServiceManager;
import com.jarvis.app.car.util.ThreadPoolManager;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {
    private View view;

    private RecyclerView carRecyclerView;

    private HomeCarItemAdapter homeCarItemAdapter;

    private ImageView iv_addCar;


    private final Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<List<Car>> messageResult = (MessageResult<List<Car>>) message.obj;
            if (!messageResult.isJudgeSuccess()) {

            } else {
                List<Car> result = messageResult.getResult();
                homeCarItemAdapter.setCars(result);
            }
        }
    };

    private final Handler deleteHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<Void> messageResult = (MessageResult<Void>) message.obj;
            if (!messageResult.isJudgeSuccess()) {
                Toast.makeText(getActivity(), messageResult.getMsg(), Toast.LENGTH_SHORT).show();
                return;
            } else {
                loadData();
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home, container, false);

        carRecyclerView = view.findViewById(R.id.carRecyclerView);
        iv_addCar = view.findViewById(R.id.iv_addCar);

        iv_addCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddCarActivity.class);
                startActivityForResult(intent, Integer.MIN_VALUE);
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        homeCarItemAdapter = new HomeCarItemAdapter(getActivity());
        carRecyclerView.setAdapter(homeCarItemAdapter);

        homeCarItemAdapter.setItemViewOnClickListener(new HomeCarItemAdapter.ItemViewOnClickListener() {
            @Override
            public void deleteOnLongClick(Car car, int position) {
                new AlertDialog.Builder(getContext())
                        .setTitle("温馨提示！")
                        .setMessage("确定删除吗？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        MessageResult<Void> listMessageResult = ServiceManager.carService.delete(AppConstant.ACCOUNT_ID,car.getId());
                                        Message msg = Message.obtain();
                                        msg.obj = listMessageResult;
                                        deleteHandler.sendMessage(msg);

                                    }
                                });
                            }
                        })
                        .show();
            }

            @Override
            public void infoOnClick(Car car, int position) {
                Intent intent = new Intent(getActivity(), CarInfoActivity.class);
                intent.putExtra("carId", car.getId());
                startActivityForResult(intent, Integer.MIN_VALUE);
            }
        });

        loadData();

        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Integer.MIN_VALUE) {
            loadData();
        }
    }

    public void loadData() {
        ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                MessageResult<List<Car>> listMessageResult = ServiceManager.carService.listAll(AppConstant.ACCOUNT_ID,AppConstant.ACCOUNT_SUPER.equals(1));
                Message msg = Message.obtain();
                msg.obj = listMessageResult;
                handler.sendMessage(msg);

            }
        });
    }
}